import { Button, message } from "antd/es";
import { useRef } from "react";
import { CHUNK_SIZE } from "./const";
import "./index.less";
import { requestInstance } from "./request";
import useDrag from "./useDrag";
import { getFileName } from "./utils";
function createFileChunks(file: File, filename: string) {
  //最后切成的分片的数组
  const chunks = [];
  //计算一共要切成多少片
  const count = Math.ceil(file.size / CHUNK_SIZE);
  for (let i = 0; i < count; i++) {
    const chunk = file.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
    chunks.push({
      chunk,
      chunkFileName: `${filename}-${i}`,
    });
  }
  return chunks;
}
async function uploadFile(file: File, filename: string) {
  const chunkList = createFileChunks(file, filename);
  const allRequest = chunkList.map(({ chunk, chunkFileName }) => {
    return requestInstance.post(
      "http://localhost:3000/upload/" + filename,
      chunk,
      {
        headers: {
          //这个请求头是告诉服务器请求体是一个二进制格式，是一个字节流
          "Content-Type": "application/octet-stream",
        },
        params: {
          //此查询参数会拼接到url地址里
          chunkFileName,
          start: 0, //把写入文件的起始位置也作为查询 参数发送给服务器
        },
      }
    );
  });
  Promise.all(allRequest).then((res) => {
    console.log(res, "上传完成");
    requestInstance
      .get("http://localhost:3000/upload/merge/" + filename)
      .then((res) => {
        console.log("合并", res);
      });
  });
}
export default function Upload() {
  const ref = useRef<HTMLDivElement>(null);
  const { filePreview, selectedFile } = useDrag(ref);
  const handleUpload = async () => {
    if (!selectedFile) {
      message.error("你尚未选中任何文件");
      return;
    }
    const fileName = await getFileName(selectedFile);
    await uploadFile(selectedFile, fileName);
  };
  return (
    <div>
      <div className="vital-upload" ref={ref}>
        {filePreview.type.startsWith("image") ? (
          <img src={filePreview.url} alt="" />
        ) : (
          ""
        )}
      </div>
      <Button type="primary" onClick={handleUpload}>
        上传
      </Button>
    </div>
  );
}
